package com.my.mymafengwo.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.smallstrong.mafengwopro.R;
import com.google.gson.Gson;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.my.mymafengwo.adapter.BaseAdapterHelper;
import com.my.mymafengwo.adapter.QuickAdapter;
import com.my.mymafengwo.adapter.StoreCityPagerAdapter;
import com.my.mymafengwo.adapter.StoreHeadPagerAdapter;
import com.my.mymafengwo.adapter.StoreThemesAdapter;
import com.my.mymafengwo.base.BaseActivity;
import com.my.mymafengwo.bean.Store;
import com.my.mymafengwo.utils.UrlUtils;
import com.my.mymafengwo.views.NoScrollListview;

import java.util.ArrayList;
import java.util.List;

/**
 * ***********************************************
 * author:ljz
 * time:2015/12/7 15:36
 * name:马蜂窝商城页面
 * step:
 * ***********************************************
 */
public class StoreActivity extends BaseActivity implements View.OnClickListener{
    private ViewPager viewPager,viewPagerCity;
    private List<Store.DataEntity.HeadimgsEntity> listHeadimgs;//页面广告数据集合
    private List<String> listHeadimgsData;//页面广告图片数据集合
    private List<ImageView> listHeadimgsImage;//页面广告图片集合
    private List<View> pointList;//小圆点集合
    private LinearLayout llPoints; // 存放导航圆点的容器
    private StoreHeadPagerAdapter adapterHeadimgs;//页面广告适配器

    private int currentPos = 0;//滚动广告的下标
    private GridView gridView;
    private Store store;//解析出来的数据
    private RadioGroup rgDestination;
    private RadioButton rbtnHot,rbtnAsia,rbtnInland,rbtnUsa;
    private List<GridView> listGridView;//GridView集合
    private List<String> listRbtn;//RadioButton数据集合
    private StoreCityPagerAdapter adapterCitys;//热门城市适配器热门城市适配器
    private List<Store.DataEntity.DestinationEntity.ItemsEntity> listGridViewCity;//城市的具体数据集合
    private QuickAdapter<Store.DataEntity.DestinationEntity.ItemsEntity> adapterItems;//具体城市使用的适配器

    private NoScrollListview lvThemes,lvList;
    private List<Store.DataEntity.ThemesEntity> listThemes;
    private StoreThemesAdapter adapterThemes;

    private List<Store.DataEntity.ListEntity> listEntity;
    private QuickAdapter<Store.DataEntity.ListEntity> adapterListEntity;

    private TextView tvSearchMore;
    private Button btnBack;
    private RelativeLayout rl;

    private static final int WHAT_NEWS_AUTO_RUN = 1;
    private static final int DELAY_TIME = 1000;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case WHAT_NEWS_AUTO_RUN: // ViewPager自动滚动
                    viewPager.setCurrentItem(currentPos + 1);
                    handler.sendEmptyMessageDelayed(WHAT_NEWS_AUTO_RUN, DELAY_TIME);
                    break;
                default:
                    break;
            }
        }
    };
    @Override
    protected void loadXml() {
        setContentView(R.layout.activity_store);
        listHeadimgs=new ArrayList<>();
        listHeadimgsData=new ArrayList<>();
        listHeadimgsImage=new ArrayList<>();
        pointList=new ArrayList<>();
        listGridView=new ArrayList<>();
        listRbtn=new ArrayList<>();
        listGridViewCity=new ArrayList<>();
        listThemes=new ArrayList<>();
        listEntity=new ArrayList<>();
        store=new Store();
        adapterHeadimgs=new StoreHeadPagerAdapter(this);
        adapterCitys=new StoreCityPagerAdapter(this);
        adapterThemes=new StoreThemesAdapter(this);
    }

    @Override
    protected void getIntentData(Bundle savedInstanceState) {

    }

    @Override
    protected void initViews() {
        viewPager = (ViewPager) findViewById(R.id.viewPager);
        viewPagerCity = (ViewPager) findViewById(R.id.viewPager_city);
        llPoints = (LinearLayout) findViewById(R.id.ll_point);
        rgDestination= (RadioGroup) findViewById(R.id.rg_destination);
        rbtnHot= (RadioButton) findViewById(R.id.rbtn_hot);
        rbtnAsia= (RadioButton) findViewById(R.id.rbtn_asia);
        rbtnUsa= (RadioButton) findViewById(R.id.rbtn_usa);
        rbtnInland= (RadioButton) findViewById(R.id.rbtn_inland);
        lvThemes= (NoScrollListview) findViewById(R.id.lv_themes);
        lvList= (NoScrollListview) findViewById(R.id.lv_list);
        tvSearchMore= (TextView) findViewById(R.id.tv_search_more);
        btnBack= (Button) findViewById(R.id.btn_back);
        rl= (RelativeLayout) findViewById(R.id.relativelayout);
    }

    @Override
    protected void registerListener() {
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }
            @Override
            public void onPageSelected(int position) {
                if (listHeadimgsImage.size() != 0) {
                    int pos = position % listHeadimgsImage.size();
                    pointList.get(currentPos % listHeadimgsImage.size()).setEnabled(false);
                    pointList.get(pos).setEnabled(true);
                    currentPos = position;
                }
            }
            @Override
            public void onPageScrollStateChanged(int state) {
                switch (state) {
                    case ViewPager.SCROLL_STATE_IDLE: // 停止
                        if(!handler.hasMessages(WHAT_NEWS_AUTO_RUN)) {
                            handler.sendEmptyMessageDelayed(WHAT_NEWS_AUTO_RUN, DELAY_TIME);
                        }
                        break;
                    case ViewPager.SCROLL_STATE_DRAGGING: // 开始拖拽
                        if(handler.hasMessages(WHAT_NEWS_AUTO_RUN)) {
                            handler.removeMessages(WHAT_NEWS_AUTO_RUN);
                        }
                        break;
                    default:
                        break;
                }
            }
        });
        rgDestination.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rbtn_hot:
                        viewPagerCity.setCurrentItem(0);
                        break;
                    case R.id.rbtn_asia:
                        viewPagerCity.setCurrentItem(1);
                        break;
                    case R.id.rbtn_usa:
                        viewPagerCity.setCurrentItem(2);
                        break;
                    case R.id.rbtn_inland:
                        viewPagerCity.setCurrentItem(3);
                        break;
                    default:
                        break;
                }
            }
        });
        viewPagerCity.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                switch (position) {
                    case 0:
                        rgDestination.check(R.id.rbtn_hot);
                        break;
                    case 1:
                        rgDestination.check(R.id.rbtn_asia);
                        break;
                    case 2:
                        rgDestination.check(R.id.rbtn_usa);
                        break;
                    case 3:
                        rgDestination.check(R.id.rbtn_inland);
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        btnBack.setOnClickListener(this);
        rl.setOnClickListener(this);
        tvSearchMore.setOnClickListener(this);
    }
    /**
     * 加载数据
     */
    @Override
    protected void initData() {
        HttpUtils get=new HttpUtils();
        get.configDefaultHttpCacheExpiry(100 * 1024);
        get.send(HttpRequest.HttpMethod.GET, UrlUtils.STORE_URL, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String result = responseInfo.result;
                adapterThemes.setString(result);
                Gson gson = new Gson();
                store = gson.fromJson(result, Store.class);
                //加载广告ViewPager
                initHeadimgs();
                //加载热门城市标题与其viewPager
                initHotCity();
                //加载最佳旅行地,热门目的地等数据
                initThemes();
                //加载东南亚悠然美地等数据
                initList();
                tvSearchMore.setVisibility(View.VISIBLE);
            }

            @Override
            public void onFailure(HttpException e, String s) {
            }
        });

    }
    /**
     * 加载最佳旅行地,热门目的地等数据
     */
    private void initList() {
        listEntity=store.getData().getList();
//        LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,4200);
//        lvList.setLayoutParams(params);
        adapterListEntity=new QuickAdapter<Store.DataEntity.ListEntity>(this,R.layout.item_themes_list2,listEntity) {
            @Override
            protected void convert(BaseAdapterHelper helper, Store.DataEntity.ListEntity item) {
                helper.setText(R.id.tv_title, item.getTitle());
                GridView gridView=helper.getView(R.id.gridView);
                gridView.setNumColumns(1);
                LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,1200);
                gridView.setLayoutParams(params);
                List<Store.DataEntity.ListEntity.ContentEntity> listContentEntity=item.getContent();
                QuickAdapter<Store.DataEntity.ListEntity.ContentEntity> adapter=new QuickAdapter<Store.DataEntity.ListEntity.ContentEntity>(StoreActivity.this,R.layout.item_list_local_product,listContentEntity) {
                    @Override
                    protected void convert(BaseAdapterHelper helper, Store.DataEntity.ListEntity.ContentEntity item) {
                        helper.setText(R.id.tv_cityname,item.getDestination());
                        helper.setText(R.id.tv_type,item.getTag_name());
                        helper.setText(R.id.tv_title,item.getTop_name());
                        helper.setText(R.id.tv_price,item.getPrice());
                        helper.setText(R.id.tv_third,item.getPrice_suffix());
                        helper.setText(R.id.tv_discount,item.getRed_str());
                        helper.setImageUrl(R.id.iv_icon,item.getImg());
                    }
                };
                gridView.setAdapter(adapter);
            }
        };
        lvList.setAdapter(adapterListEntity);
    }

    /**
     * 加载最佳旅行地,热门目的地等数据
     */
    private void initThemes() {
        listThemes=store.getData().getThemes();
//        LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,2000);
//        lvThemes.setLayoutParams(params);
        adapterThemes.setList(listThemes);
        lvThemes.setAdapter(adapterThemes);
    }

    /**
     * 加载具体城市数据
     */
    private void initCityData(int i) {
        listGridViewCity=store.getData().getDestination().get(i).getItems();
        adapterItems=new QuickAdapter<Store.DataEntity.DestinationEntity.ItemsEntity>(this,R.layout.item_search_city,listGridViewCity) {
            @Override
            protected void convert(BaseAdapterHelper helper, Store.DataEntity.DestinationEntity.ItemsEntity item) {
                if(item.getName().equals("更多")){
                    helper.setBackgroundRes(R.id.tv_hot,R.mipmap.mall_home_destination_more);
                }else{
                    helper.setBackgroundRes(R.id.tv_hot,R.drawable.shape_local_product_more);
                }
                helper.setText(R.id.tv_hot,item.getName());
            }
        };
        gridView.setAdapter(adapterItems);
    }

    /**
     * 加载热门城市ViewPager
     */
    private void initHotCity() {
        rgDestination.check(R.id.rbtn_hot);
        viewPagerCity.removeAllViews();
        List<Store.DataEntity.DestinationEntity> listDestination=store.getData().getDestination();
        for(int i=0;i<listDestination.size();i++){
            gridView=new GridView(this);
            gridView.setNumColumns(4);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            gridView.setLayoutParams(params);
            //加载具体城市数据
            initCityData(i);
            listGridView.add(gridView);
            viewPagerCity.addView(gridView);
            listRbtn.add(listDestination.get(i).getTitle());
        }
        adapterCitys.setData(listGridView);
        rbtnHot.setText(listRbtn.get(0));
        rbtnAsia.setText(listRbtn.get(1));
        rbtnUsa.setText(listRbtn.get(2));
        rbtnInland.setText(listRbtn.get(3));
        viewPagerCity.setAdapter(adapterCitys);
    }

    /**
     * 加载广告ViewPager
     */
    private void initHeadimgs() {
        listHeadimgs = store.getData().getHeadimgs();
        for (int i = 0; i < listHeadimgs.size(); i++) {
            listHeadimgsData.add(listHeadimgs.get(i).getFit_src().getUrl());
        }

        loaderHeadingsImage();
        currentPos = Integer.MAX_VALUE / 2 - Integer.MAX_VALUE / 2 % listHeadimgsImage.size();
        loaderPoints();

        viewPager.setAdapter(adapterHeadimgs);
        viewPager.setCurrentItem(currentPos, false);
    }

    /**
     * 加载小圆点
     */
    private void loaderPoints() {
        for (int i = 0; i < listHeadimgsImage.size(); i++) {
            View point = new View(this);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(20, 20);
            params.leftMargin = 4;
            params.rightMargin = 4;
            point.setLayoutParams(params);
            point.setBackgroundResource(R.drawable.selector_local_point);
            int pos = currentPos % listHeadimgsImage.size();
            if(i == pos) {
                point.setEnabled(true);
            } else {
                point.setEnabled(false);
            }
            pointList.add(point);
            // 将圆点添加到容器中
            llPoints.addView(point);
        }
    }

    /**
     * 加载广告图片
     */
    private void loaderHeadingsImage() {
        for(int i=0;i<listHeadimgsData.size();i++){
            BitmapUtils bit=new BitmapUtils(this);
            ImageView iv = new ImageView(this);
            bit.display(iv,listHeadimgsData.get(i));
            iv.setScaleType(ImageView.ScaleType.FIT_XY);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                    50);
            iv.setLayoutParams(params);
            listHeadimgsImage.add(iv);
            adapterHeadimgs.setData(listHeadimgsImage);
        }
    }

    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.btn_back:
                finish();
                break;
            case R.id.relativelayout:
                startActivity(new Intent(StoreActivity.this,StartSearchActivity.class));
                break;
            case R.id.tv_search_more:
                startActivity(new Intent(StoreActivity.this,StartSearchActivity.class));
                break;
        }
    }
}
